﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Util;
using NPOI.POIFS.FileSystem;
using NPOI.HPSF;


public partial class UC_ucBCL_NVKD : System.Web.UI.UserControl
{
    SqlParameter[] p;
    clsXuLy ex = new clsXuLy();
    NpoiExport cl = new NpoiExport();
    string frmName = "frmBaoCaoLuong";
    static int f_SuDung = 0, f_XemTatCa = 0, f_InBaoCao = 0;
    public string Header = System.Configuration.ConfigurationSettings.AppSettings["Header"].ToString();

    static System.Data.DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Convert.ToString(Session["user"])) || string.IsNullOrEmpty(Convert.ToString(Session["IDUser"])))
            Response.Redirect("Default.aspx");
        if (!IsPostBack)
        {
            string idnguoidung = Session["IDUser"].ToString();
            string sql = "select SuDung,Them,Sua,Xoa,InBaoCao,XemTatCa from XDAPhanQuyen where IDnguoidung='" + idnguoidung + "' and tag='" + frmName + "'";

            System.Data.DataTable dt2 = ex.GetData_Text(sql);
            if (dt2.Rows.Count > 0)
            {
                f_SuDung = int.Parse(dt2.Rows[0]["SuDung"].ToString());
                f_InBaoCao = int.Parse(dt2.Rows[0]["InBaoCao"].ToString());
                f_XemTatCa = int.Parse(dt2.Rows[0]["XemTatCa"].ToString());
            }

            for (int i = 1; i <= 12; i++)
            {
                dlThang.Items.Add(new ListItem("Tháng " + i.ToString(), i.ToString()));
            }
            dlThang.Items.Insert(0, new ListItem("--Chọn tháng--", ""));
            dlThang.SelectedIndex = 0;

            int year1 = DateTime.Now.Year - 3;
            int year2 = DateTime.Now.Year;
            for (int i = year2; i >= year1; i--)
            {
                dlNam.Items.Add(new ListItem("Năm " + i.ToString(), i.ToString()));
            }
            dlNam.SelectedValue = year2.ToString();

            LoadNhanVienKD(dlNhanVien);

        }
    }

    void LoadNhanVienKD(DropDownList dlLaiXe)
    {
        if (dlThang.SelectedIndex > 0)
        {
            getDate();
            p = new SqlParameter[2];
            p[0] = new SqlParameter("@Thang", int.Parse(dlThang.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(dlNam.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;

            dlLaiXe.Items.Clear();
            dlLaiXe.DataSource = ex.GetData("sp_BCL_NVKD_LoadNVKD", p);
            dlLaiXe.DataBind();
            dlLaiXe.Items.Insert(0, new ListItem("--Chọn nhân viên KD--", ""));
            dlLaiXe.SelectedIndex = 0;
        }
        else
        {
            dlLaiXe.Items.Clear();
            dlLaiXe.Items.Insert(0, new ListItem("--Chọn nhân viên KD--", ""));
            dlLaiXe.SelectedIndex = 0;
        }
    }
    protected void dlThang_SelectedIndexChanged(object sender, EventArgs e)
    {

        LoadNhanVienKD(dlNhanVien);
    }
    private void gstGetMess(string gstMess, string gstLink)
    {
        if (gstLink == "")
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "')", true);
        else
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "');window.location.href='" + gstLink + "'", true);

    }
    public void getDate()
    {
        if (dlThang.SelectedIndex.Equals(0))
        {
            hdTuNgay.Value = "";
            hdDenNgay.Value = "";
        }
        else
        {
            hdTuNgay.Value = "1/" + dlThang.SelectedValue + "/" + dlNam.SelectedValue;
            hdDenNgay.Value = GetLastDayOfMonth(int.Parse(dlThang.SelectedValue)).ToString("dd/MM/yyyy");
        }
    }
    public DateTime GetLastDayOfMonth(int iMonth)
    {
        DateTime dtResult = new DateTime(int.Parse(dlNam.SelectedValue), iMonth, 1);
        dtResult = dtResult.AddMonths(1);
        dtResult = dtResult.AddDays(-(dtResult.Day));
        return dtResult;
    }

    protected void btnXem_Click(object sender, EventArgs e)
    {
        if (dlThang.SelectedIndex > 0)
        {
            p = new SqlParameter[4];
            p[0] = new SqlParameter("@Thang", int.Parse(dlThang.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(dlNam.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;
            p[2] = new SqlParameter("@NhanVien", ex.GetGuid(dlNhanVien.SelectedValue));
            p[2].SqlDbType = SqlDbType.UniqueIdentifier;
            p[3] = new SqlParameter("@Index", dlNhanVien.SelectedIndex > 0 ? 1 : 2);
            p[3].SqlDbType = SqlDbType.Int;
            GV.DataSource = ex.GetData("sp_BCL_NVKD", p);
            GV.DataBind();
        }
        else gstGetMess("Chọn tháng", "");
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        if (dlThang.SelectedIndex > 0)
        {
            p = new SqlParameter[4];
            p[0] = new SqlParameter("@Thang", int.Parse(dlThang.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(dlNam.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;
            p[2] = new SqlParameter("@NhanVien", ex.GetGuid(dlNhanVien.SelectedValue));
            p[2].SqlDbType = SqlDbType.UniqueIdentifier;
            p[3] = new SqlParameter("@Index", dlNhanVien.SelectedIndex > 0 ? 1 : 2);
            p[3].SqlDbType = SqlDbType.Int;

            dt = ex.GetData("sp_BCL_NVKD", p);
            PrintNPOI(dt);
        }
        else gstGetMess("Chọn tháng", "");
    }
    void PrintNPOI(System.Data.DataTable dt)
    {

        if (dt.Rows.Count > 0)
        {
            var workbook = new HSSFWorkbook();
            string sheetname = "BCL-NVKD";

            if (dlNhanVien.SelectedIndex > 0)
                sheetname = "BCL-NVKD-" + dlNhanVien.SelectedItem.Text;

            var sheet = workbook.CreateSheet(sheetname);

            #region CSS
            var headerLabelCellStyle = workbook.CreateCellStyle();
            headerLabelCellStyle.Alignment = HorizontalAlignment.LEFT;
            headerLabelCellStyle.BorderBottom = CellBorderType.THIN;
            headerLabelCellStyle.BorderLeft = CellBorderType.THIN;
            headerLabelCellStyle.BorderRight = CellBorderType.THIN;
            headerLabelCellStyle.BorderTop = CellBorderType.THIN;

            var headerLabelFont = workbook.CreateFont();
            headerLabelFont.FontName = "Times New Roman";

            headerLabelFont.FontHeightInPoints = 11;
            headerLabelFont.Color = HSSFColor.BLACK.index;
            headerLabelCellStyle.SetFont(headerLabelFont);

            //--------------------------

            var hsRight = workbook.CreateCellStyle();
            hsRight.Alignment = HorizontalAlignment.RIGHT;
            hsRight.BorderBottom = CellBorderType.THIN;
            hsRight.BorderLeft = CellBorderType.THIN;
            hsRight.BorderRight = CellBorderType.THIN;
            hsRight.BorderTop = CellBorderType.THIN;

            hsRight.SetFont(headerLabelFont);
            //-------------------
            var hsCenter = workbook.CreateCellStyle();
            hsCenter.Alignment = HorizontalAlignment.CENTER;
            hsCenter.BorderBottom = CellBorderType.THIN;
            hsCenter.BorderLeft = CellBorderType.THIN;
            hsCenter.BorderRight = CellBorderType.THIN;
            hsCenter.BorderTop = CellBorderType.THIN;

            hsCenter.SetFont(headerLabelFont);
            //-----------------------

            var hs1 = workbook.CreateCellStyle();
            hs1.Alignment = HorizontalAlignment.LEFT;

            var hsb = workbook.CreateFont();
            hsb.Boldweight = (short)FontBoldWeight.BOLD;
            hsb.FontName = "Times New Roman";

            hsb.FontHeightInPoints = 11;
            hsb.Color = HSSFColor.BLACK.index;
            hs1.SetFont(hsb);

            //-------------
            var hs2 = workbook.CreateCellStyle();
            hs2.Alignment = HorizontalAlignment.CENTER;

            var hsb2 = workbook.CreateFont();
            hsb2.Boldweight = (short)FontBoldWeight.BOLD;
            hsb2.FontName = "Times New Roman";

            hsb2.FontHeightInPoints = 18;
            hsb2.Color = HSSFColor.BLACK.index;
            hs2.SetFont(hsb2);
            //------------------------------
            var hs3 = workbook.CreateCellStyle();
            hs3.Alignment = HorizontalAlignment.CENTER;
            var hsb3 = workbook.CreateFont();
            hsb3.Boldweight = (short)FontBoldWeight.BOLD;
            hsb3.FontName = "Times New Roman";

            hsb3.FontHeightInPoints = 14;
            hsb3.Color = HSSFColor.BLACK.index;
            hs3.SetFont(hsb3);

            //----------------------------
            var hs4 = workbook.CreateCellStyle();
            hs4.Alignment = HorizontalAlignment.CENTER;

            hs4.BorderBottom = CellBorderType.THIN;
            hs4.BorderLeft = CellBorderType.THIN;
            hs4.BorderRight = CellBorderType.THIN;
            hs4.BorderTop = CellBorderType.THIN;

            var hsb4 = workbook.CreateFont();
            hsb4.Boldweight = (short)FontBoldWeight.BOLD;
            hsb4.FontName = "Times New Roman";

            hsb4.FontHeightInPoints = 11;
            hsb4.Color = HSSFColor.BLACK.index;
            hs4.SetFont(hsb4);

            #endregion

            //Start header-----------------------------------------------------------------------
            #region Header
            //tao hnag dau tien
            var rowIndex = 0;

            //cong ty
            var row = sheet.CreateRow(rowIndex);
            Cell r1c1 = row.CreateCell(0);
            r1c1.SetCellValue("Công ty cổ phần Xây Dựng Đức Anh");
            r1c1.CellStyle = hs1;
            r1c1.Row.Height = 400;

            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 4);
            sheet.AddMergedRegion(cra);

            //chi nhanh
            rowIndex++;
            row = sheet.CreateRow(rowIndex);
            r1c1 = row.CreateCell(0);
            r1c1.SetCellValue("Chi nhánh Trạm trộn Lâm Thao");
            r1c1.CellStyle = hs1;
            r1c1.Row.Height = 400;

            cra = new CellRangeAddress(1, 1, 0, 4);
            sheet.AddMergedRegion(cra);

            //tieu de bao cao
            string ngaythang = dlThang.SelectedItem.Text.ToUpper() + " " + dlNam.SelectedItem.Text.ToUpper();
            rowIndex++;
            row = sheet.CreateRow(rowIndex);
            r1c1 = row.CreateCell(0);
            r1c1.SetCellValue("BÁO CÁO LƯƠNG NHÂN VIÊN KINH DOANH " + ngaythang);
            r1c1.CellStyle = hs2;
            r1c1.Row.Height = 500;

            cra = new CellRangeAddress(2, 2, 0, 14);
            sheet.AddMergedRegion(cra);

            //if (dlNhanVien.SelectedIndex > 0)
            //{
            //    //bien so
            //    rowIndex++;
            //    row = sheet.CreateRow(rowIndex);
            //    r1c1 = row.CreateCell(0);
            //    r1c1.SetCellValue(dlNhanVien.SelectedIndex > 0 ? "Nhân viên: " + dlNhanVien.SelectedItem.Text : "");
            //    r1c1.CellStyle = hs3;
            //    r1c1.Row.Height = 500;

            //    cra = new CellRangeAddress(3, 3, 0, 14);
            //    sheet.AddMergedRegion(cra);
            //}


            //freeze panes
            sheet.CreateFreezePane(0, 6);
            #endregion


            #region Header1-2

            //header2
            rowIndex++;
            row = sheet.CreateRow(rowIndex);

            var cell = row.CreateCell(0);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(1);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(2);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(3);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(5);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(7);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(8);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(10);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(12);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(13);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(4);
            cell.SetCellValue("Khối thứ 100");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cra = new CellRangeAddress(3, 3, 4, 5);
            sheet.AddMergedRegion(cra);

            cell = row.CreateCell(6);
            cell.SetCellValue("Khối thứ 101 tự mang về");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;
            cra = new CellRangeAddress(3, 3, 6, 8);
            sheet.AddMergedRegion(cra);



            cell = row.CreateCell(9);
            cell.SetCellValue("Thưởng");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;
            cra = new CellRangeAddress(3, 3, 9, 10);
            sheet.AddMergedRegion(cra);

            cell = row.CreateCell(11);
            cell.SetCellValue("Sai đi kí HĐ");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;
            cra = new CellRangeAddress(3, 3, 11, 13);
            sheet.AddMergedRegion(cra);

            cell = row.CreateCell(14);
            cell.SetCellValue("TT chênh");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            cell = row.CreateCell(15);
            cell.SetCellValue("");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;


            rowIndex++;
            row = sheet.CreateRow(rowIndex);
            string[] header = { "Họ tên", "Bộ phận", "Chức vụ", "Lương cơ bản", "Phụ cấp", "Khối lượng", "Đơn giá", "Thành tiền", ">1000", "<1000", "Khối lượng", "Đơn giá", "Thành tiền","", "Tổng tiền" };

            cell = row.CreateCell(0);
            cell.SetCellValue("STT");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;


            //tao tieu de cot
            for (int j = 0; j < header.Length; j++)
            {
                cell = row.CreateCell(j + 1);
                cell.SetCellValue(header[j].ToString());
                cell.CellStyle = hs4;
                cell.Row.Height = 500;
                sheet.AutoSizeColumn(j);
            }
            #endregion
            //End header-----------------------------------------------------------------------
            //ghi du lieu tung dong
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                rowIndex++;
                row = sheet.CreateRow(rowIndex);
                cell = row.CreateCell(0);
                cell.SetCellValue((i + 1).ToString());
                cell.CellStyle = hsCenter;

                for (int j = 1; j < dt.Columns.Count - 1; j++)
                {
                    cell = row.CreateCell(j);

                    if (j >= 4)
                    {
                        if (!dt.Rows[i][j + 1].ToString().Trim().Equals(""))
                        {
                            cell.SetCellType(CellType.NUMERIC);
                            cell.SetCellValue(double.Parse(dt.Rows[i][j + 1].ToString()));
                        }
                        else
                            cell.SetCellValue(dt.Rows[i][j + 1].ToString());
                        cell.CellStyle = hsRight;
                    }
                    else
                    {
                        cell.SetCellValue(dt.Rows[i][j + 1].ToString());

                        cell.CellStyle = headerLabelCellStyle;
                    }
                    cell.Row.Height = 500;
                }

            }

            #region Footer

            rowIndex++;
            row = sheet.CreateRow(rowIndex);

            cell = row.CreateCell(1);
            cell.SetCellValue("Tổng cộng");
            cell.Row.Height = 500;
            cell.CellStyle = hs4;

            string[] footer = { "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O","P" };
            for (int k = 4; k <= 15; k++)
            {
                if (k != 7 && k != 12)
                {
                    cell = row.CreateCell(k);
                    cell.CellFormula = "SUM(" + footer[k - 4] + "6:" + footer[k - 4] + rowIndex.ToString() + ")";
                    cell.Row.Height = 500;
                    cell.CellStyle = hs4;
                }
            }


            for (int ik = 0; ik < dt.Columns.Count; ik++)
            {
                //fix lai border
                if (ik == 0 || ik == 2 || ik == 3 || ik == 7 || ik == 12)
                {
                    r1c1 = row.CreateCell(ik);
                    r1c1.CellStyle = hs4;
                    r1c1.Row.Height = 400;
                }
                sheet.AutoSizeColumn(ik);
            }
            #endregion

            //end sheet tong hop--------------------------
            using (var exportData = new MemoryStream())
            {
                workbook.Write(exportData);
                string filename = dlNhanVien.SelectedIndex > 0 ? dlNhanVien.SelectedItem.Text : "";
                string saveAsFileName = "BCL-NVKD-" + filename + " " + ngaythang + ".xls";

                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
                Response.Clear();
                Response.BinaryWrite(exportData.GetBuffer());
                Response.End();
            }
        }
        else
            gstGetMess("Không có dữ liệu nào để in", "");
    }
    protected void GV_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#EEFFAA'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");
        }
    }
    protected void GV_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
            HeaderGridRow.Height = 20;
            HeaderGridRow.HorizontalAlign = HorizontalAlign.Center;
            TableCell HeaderCell = new TableCell();

            HeaderGridRow.Cells.Add(HeaderCell);
            HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.ColumnSpan = 3;


            HeaderGridRow.Cells.Add(HeaderCell);
            HeaderCell = new TableCell();
            HeaderCell.Text = "Khối thứ 100 tự mang về";
            HeaderCell.ColumnSpan = 2;


            HeaderGridRow.Cells.Add(HeaderCell);
            HeaderCell = new TableCell();
            HeaderCell.Text = "Khối thứ 101 tự mang về";
            HeaderCell.ColumnSpan = 3;


            HeaderGridRow.Cells.Add(HeaderCell);
            HeaderCell = new TableCell();
            HeaderCell.Text = "Thưởng vượt mức";
            HeaderCell.ColumnSpan = 2;

            HeaderGridRow.Cells.Add(HeaderCell);
            HeaderCell = new TableCell();
            HeaderCell.Text = "Sai đi kí HĐ";
            HeaderCell.ColumnSpan = 3;

            HeaderGridRow.Cells.Add(HeaderCell);
            HeaderCell = new TableCell();
            HeaderCell.Text = "TT Chênh";
            HeaderCell.ColumnSpan = 1;

            HeaderGridRow.Cells.Add(HeaderCell);
            HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.ColumnSpan = 1;
            HeaderGridRow.Cells.Add(HeaderCell);
            HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.ColumnSpan = 1;

            GV.Controls[0].Controls.AddAt(0, HeaderGridRow);
        }
    }
}